<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useColumns } from "./columns";
import "plus-pro-components/es/components/search/style/css";
import Plus from "~icons/ep/plus";
import { addCoupon, updateCoupon, couponInfo } from "@/api/coupon";

defineOptions({
  name: "DiscountCoupon"
});
import {
  type PlusColumn,
  type FieldValues,
  PlusDialogForm,
  PlusSearch
} from "plus-pro-components";
import { ElMessage } from "element-plus";
import { router } from "@/router";
import { useMenu } from "@/utils/power";
import { useRoute } from "vue-router";
import { start } from "nprogress";
const power = useMenu(["add", "edit", "info"]);

const route = useRoute();
const status = route.query.status ? Number(route.query.status) : undefined;

const tableRef = ref();
console.log(status, "status");
const defaultSearchState = ref({});
const searchState = ref({ status: status || undefined });
const searchColumns: PlusColumn[] = [
  // {
  //   label: "姓名",
  //   width: 200,
  //   prop: "realName",
  //   valueType: "input"
  // },
  // {
  //   label: "手机号",
  //   width: 200,
  //   prop: "mobile",
  //   valueType: "input"
  // },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    defaultValue: status || null,
    options: [
      {
        label: "激活",
        value: 1,
        color: "red"
      },
      {
        label: "未激活",
        value: 2,
        color: "red"
      },
      {
        label: "已过期",
        value: 3,
        color: "red"
      },
      {
        label: "已删除",
        value: 4,
        color: "red"
      }
    ]
  }
];

const rules = {
  couponName: [
    {
      required: true,
      message: "优惠券名称必填"
    }
  ],
  status: [
    {
      required: true,
      message: "状态必选"
    }
  ],
  description: [
    {
      required: true,
      message: "优惠券描述必填"
    }
  ],
  type: [
    {
      required: true,
      message: "优惠券类型必填"
    }
  ],
  value: [
    {
      required: true,
      message: "优惠券价值必填"
    }
  ],
  usageLimit: [
    {
      required: true,
      message: "可使用次数必填"
    }
  ],
  perUserLimit: [
    {
      required: true,
      message: "每人可使用次数必填"
    }
  ],
  validFrom: [
    {
      required: true,
      message: "有效期开始时间必填"
    }
  ],
  validTo: [
    {
      required: true,
      message: "有效期结束时间必填"
    }
  ],
  applicableProducts: [
    {
      required: true,
      message: "适用商品必填"
    }
  ],
  source: [
    {
      required: true,
      message: "优惠券来源必填"
    }
  ],
  startTime: [
    {
      required: true,
      message: "开始时间必填"
    }
  ],
  endTime: [
    {
      required: true,
      message: "结束时间必填"
    }
  ]
};

const edit = ref(false);
const confirmLoading = ref(false);
const visible = ref(false);
const values = ref<FieldValues>({});
const formRef = ref();
const formColumns: PlusColumn[] = [
  {
    label: "名称",
    prop: "couponName",
    valueType: "input",
    tooltip: "请输入名称"
  },
  {
    label: "描述",
    prop: "description",
    valueType: "input",
    tooltip: "请输入描述"
  },
  {
    label: "类型",
    prop: "type",
    valueType: "select",
    options: [
      { label: "折扣", value: 1 },
      { label: "固定金额", value: 2 },
      { label: "免运费", value: 3 },
      { label: "赠品", value: 4 },
      { label: "返现", value: 5 }
    ],
    tooltip: "请选择类型"
  },
  {
    label: "价值",
    prop: "value",
    valueType: "input",
    tooltip: "请输入优惠券价值"
  },
  {
    label: "可使用次数",
    prop: "usageLimit",
    valueType: "input",
    tooltip: "请输入可使用次数"
  },
  {
    label: "每人可使用次数",
    prop: "perUserLimit",
    valueType: "input",
    tooltip: "请输入每人可使用次数"
  },
  {
    label: "有效期开始时间",
    prop: "validFrom",
    valueType: "date-picker",
    tooltip: "请选择有效期开始时间",
    fieldProps: {
      type: "datetime",
      placeholder: "有效期开始时间",
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss"
    }
  },
  {
    label: "有效期结束时间",
    prop: "validTo",
    valueType: "date-picker",
    tooltip: "请选择有效期结束时间",
    fieldProps: {
      type: "datetime",
      placeholder: "有效期结束时间",
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss"
    }
  },
  {
    label: "开始时间",
    labelWidth: 120,
    width: 600,
    prop: "startTime",
    valueType: "date-picker",
    tooltip: "请选择时间段",
    fieldProps: {
      type: "datetime",
      placeholder: "开始时间",
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss"
    }
  },
  {
    label: "结束时间",
    labelWidth: 120,
    width: 600,
    prop: "endTime",
    valueType: "date-picker",
    tooltip: "请选择时间段",
    fieldProps: {
      type: "datetime",
      placeholder: "结束时间",
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss"
    }
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "激活",
        value: 1
      },
      {
        label: "未激活",
        value: 2
      },
      {
        label: "已过期",
        value: 3
      },
      {
        label: "已删除",
        value: 4
      }
    ]
  },
  {
    label: "来源",
    prop: "source",
    valueType: "select",
    options: [
      {
        label: "活动发放",
        value: "PROMOTION"
      },
      {
        label: "注册送",
        value: "REGISTRATION"
      },
      {
        label: "充值送",
        value: "RECHARGE"
      },
      {
        label: "后台手动发放",
        value: "MANUAL"
      }
    ]
  },
  {
    label: "适用范围",
    prop: "applicableProducts",
    valueType: "select",
    options: [
      {
        label: "所有商品",
        value: "all"
      },
      {
        label: "金融商品",
        value: "finance"
      },
      {
        label: "商城",
        value: "shop"
      },
      {
        label: "会议",
        value: "meeting"
      },
      {
        label: "旅游",
        value: "tourism"
      }
    ]
  }
];

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  loadData,
  onSizeChange,
  onKeywordChange,
  onCurrentChange
} = useColumns();

const columnsRef = computed(() => {
  return columns;
  // if (power.value.view) {
  //   return columns;
  // }
  // const columnsCopy = [...columns];
  // return columnsCopy.slice(0, -1);
});

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};

function detailClick(row) {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  router.push({ name: "CouponDetail", query: { id: row.couponId } });
}

const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (target.prop == "realName" || target.prop == "mobile") {
    return;
  }
  onKeywordChange(value);
};

const editClick = async row => {
  try {
    const res = await couponInfo(row.couponId);
    const data = res.data;
    values.value = data;
    edit.value = true;
    visible.value = true;
  } catch (error) {
    console.error(error);
  }
};
const add = () => {
  edit.value = false;
  values.value = { status: 1, usageLimit: 0, perUserLimit: 0 };
  visible.value = true;
};
const handleSubmit = async (value: FieldValues) => {
  console.log("提交", edit.value);
  if (edit.value) {
    const updatedValues = {
      couponId: values.value.couponId,
      couponName: values.value.couponName,
      description: values.value.description,
      status: values.value.status,
      type: values.value.type,
      value: values.value.value,
      usageLimit: values.value.usageLimit,
      perUserLimit: values.value.perUserLimit,
      validFrom: values.value.validFrom,
      validTo: values.value.validTo,
      applicableProducts: values.value.applicableProducts,
      source: values.value.source,
      startTime: values.value.startTime,
      endTime: values.value.endTime
    };

    confirmLoading.value = true;
    try {
      await updateCoupon(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    const updatedValues = { ...values.value };
    confirmLoading.value = true;
    try {
      await addCoupon(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};
const handleCancel = () => {
  console.log("取消");
};

onMounted(() => {
  onKeywordChange(searchState.value);
});
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>活动券管理</h3>
        </template>
        <template v-if="power.add" #extra>
          <div class="flex flex-row items-end justify-end">
            <el-button type="primary" @click="add">
              <el-icon :size="15" color="#fff">
                <IconifyIconOffline :icon="Plus" />
              </el-icon>
              添加活动券
            </el-button>
          </div>
        </template>
        <PlusSearch
          v-model="searchState"
          :defaultValues="defaultSearchState"
          class="mt-5"
          :has-unfold="false"
          :columns="searchColumns"
          @search="handleSearch"
          @change="handleChange"
          @reset="handleReset"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :fit="true"
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #operation="{ row }">
        <el-button
          v-if="power.info"
          type="info"
          size="small"
          @click="detailClick(row)"
        >
          详情
        </el-button>
        <el-button
          v-if="power.edit"
          type="primary"
          size="small"
          @click="editClick(row)"
        >
          编辑
        </el-button>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{
        columns: formColumns,
        rules,
        labelWidth: 120
      }"
      :dialog="{ confirmLoading }"
      :title="edit ? '编辑活动券' : '添加活动券'"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    />
  </ElCard>
</template>

<style scoped>
:deep(.el-descriptions),
:deep(.el-descriptions__table tr) {
  --el-card-bg-color: transparent !important;
  --el-fill-color-blank: transparent !important;
  background: transparent !important;
}
.wrap-text {
  white-space: normal !important; /* 允许自动换行 */
  word-break: break-all; /* 强制换行 */
}
:deep(video) {
  width: 100% !important;
}
</style>
